$(function()
{
	
	$(".left ul li").click(function(event){
		$(this).addClass("currentClassLi").siblings().removeClass();
		//ajax请求得到mydata
		var mydata;
		ajaxLoadTableData(mydata);
	});
	/**
	 * 解放网Ajax请求
	 */
	function ajaxLoadTableData(mydata){
		var selectDate=$('.currentClassLi').html();
		if(selectDate==null)return;
		jQuery("#gridTable").clearGridData();//清空数据
		//ajax请求
		 $.ajax({
	         type:"get",
	         url: '/urltrace/newstrace/originalnews?date='+selectDate,
	         data:null,
	         async: false,
	         datatype: "json",
	         success:function(data){
	        	 if(data=='nologin'){
					 window.location="/urltrace/newstrace/welcome";
//					 return;
				 }
	        	var json=JSON.parse(data);
	        	if(json.type=='failure'){
	        			alert(json.info);
	        			return;
	        	}else{
	        		mydata=json;
	        	}
	         },
	         error:function(){
	        	 alert("网络繁忙，请重试！");
	         }
	     });
		for(var i=0;i<=mydata.length;i++){
			try{
				jQuery("#gridTable").setGridParam({rowNum:20}).trigger("reloadGrid").jqGrid('addRowData',mydata[i].url_crc,mydata[i]);
				//jQuery("#gridTable").jqGrid('addRowData',mydata[i].url_crc,mydata[i]);
			}catch (exception) {
				// TODO: handle exception
			}
		}
	}
	$("#gridTable").jqGrid({
		datatype: "local",
		height: "auto",
		 colModel: [
                    {
                   	 name:'url_crc',
                   	 key: true, 
                   	 hidden:true
                    },
                   {   label : "新闻标题",
						//sorttype: 'integer',
						name: 'title', 
						width: 550,
						align:'left'
					},
                   { 
						label: "发布时间",
                       name: 'date',
                       width: 300,
                       sortable:true,
						sorttype:'date',
						formatter: 'date',
						align:'left',
						formatoptions:{srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'},
                       searchoptions: {
                           dataInit: function (element) {
                              $(element).datepicker({
									autoclose: true,
									format: 'd/m/yyyy',
									orientation : 'bottom'
                               });
                           }
                       }
                   },                    
                   {
						label: "转载量",
						sorttype: 'number',
						align:'center',
						name: 'reprintNum', width: 300 }
               ],
		search : {
		 caption: "Search...",
		  Find: "Find",
		  Reset: "Reset",
		  odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'],

		  groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ],
		  matchText: " match",
		  rulesText: " rules"
	   },
	   sortname:'date',
		sortorder:'asc',
		viewrecords:true,
		rowNum:20,
		rownumbers : true,
		rowList:[10,20,30],
		multiselect: false,
		subGrid : true,
		subGridRowExpanded: showChildGrid ,
        subGridOptions: {
 		reloadOnExpand : false,
 		selectOnExpand : true
        },
		pager:"#gridPager",
		caption: "原创文章"
	}).navGrid('#gridPager',{edit:false,add:false,del:false}).navButtonAdd('#gridPager',{
		caption:"导出本页数据",
		buttonicon:"ui-icon-excel",
		onClickButton: function(){
			var title = "新闻信息";
			getXlsFromTbl('gridTable', 'right_TableData', title, true);
			//ExportTable(title, "", "gridTable", true);
		},
		position:"last"
	});
//解放网
    function showChildGrid(parentRowID, parentRowKey) {
        var childGridID = parentRowID + "_table";
        var childGridPagerID = parentRowID + "_pager";
        var childGridURL = parentRowKey+".json";
        $('#' + parentRowID).append('<table id=' + childGridID + '></table><div id=' + childGridPagerID + ' class=scroll></div>');
        $("#" + childGridID).jqGrid({
            url:"/urltrace/newstrace/reprintnews?url_crc="+parentRowKey,
            mtype: "GET",
            datatype: "json",
            page: 1,
            colNames: ['标题','作者','媒体名称','内容来源','时间'],
			colModel: [
				{name:"title",index:"title",width:200,key:true,align:"left"},
				{name:"author",index:"author",width:50,align:"left"},
				{name:"media_name",index:"media_name",width:50,align:"left"},
				{name:"content_media_name",index:"content_media_name",width:70,align:"left"},
				{name:"uni_release_date",index:"uni_release_date",width:100,align:"left",sortable:true,sorttype:'date',formatter: 'date',
					formatoptions:{srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s'}}
				
			],
			loadonce: true,
            width: 800,
            sortname: 'uni_release_date',
		    sortorder: "asc",
		    prmNames: {search: "search"},
		    rowNum: 500,
		    viewrecords: true,
		    rownumbers : true,
            height: '100%'
        });
    }
    
    //导出excel
	function getXlsFromTbl(inTblId, inTblContainerId, title, rownumbers) {
		if ($.browser.msie) { //如果是IE浏览器
			try {
				var allStr = "";
				var curStr = "";
				//alert("getXlsFromTbl");
				if (inTblId != null && inTblId != "" && inTblId != "null") {
					curStr = getTblData($('#' + inTblId), $('#' + inTblContainerId), rownumbers);
				}
				if (curStr != null) {
					allStr += curStr;
				}
				else {
					alert("你要导出的表不存在！");
					return;
				}
				var fileName = getExcelFileName(title);
				doFileExport(fileName, allStr);
			}
			catch (e) {
				alert("导出发生异常:" + e.name + "->" + e.description + "!");
			}
		} else {
//			window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$=right_TableData]').html()));
			window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('div[id$='+inTblContainerId+']').html()));
		}
	}
	function getTblData(curTbl, curTblContainer, rownumbers) {

		var outStr = "";
		if (curTbl != null) {
			var rowdata = curTbl.getRowData();
			var Lenr = 1;

			for (i = 0; i < Lenr; i++) {
				//var Lenc = curTbl.rows(i).cells.length;
				var th;
				if (rownumbers == true) {
					th = curTblContainer.find('TH:not(:first-child)');
				}
				else {
					th = curTblContainer.find('TH');
				}
				th.each(function(index, element) {
					//alert($(element).text());
					//取得每行的列数
					var j = index + 1;
					var content = $(element).text();
					//alert(j + "|" + content);
					outStr += content + "\t";
					//赋值

				});
				outStr += "\r\n";
			}
			var tmp = "";
			for (i = 0; i < rowdata.length; i++) {
				var row = eval(rowdata[i]);
				for (var each in row) {
					outStr += row[each] + "\t";
				}
				outStr += "\r\n";
			}


		}
		else {
			outStr = null;
			alert(inTbl + "不存在!");
		}
		return outStr;
	}
	function getExcelFileName(title) {
		var d = new Date();
		var curYear = d.getYear();
		var curMonth = "" + (d.getMonth() + 1);
		var curDate = "" + d.getDate();
		var curHour = "" + d.getHours();
		var curMinute = "" + d.getMinutes();
		var curSecond = "" + d.getSeconds();
		if (curMonth.length == 1) {
			curMonth = "0" + curMonth;
		}
		if (curDate.length == 1) {
			curDate = "0" + curDate;
		}
		if (curHour.length == 1) {
			curHour = "0" + curHour;
		}
		if (curMinute.length == 1) {
			curMinute = "0" + curMinute;
		}
		if (curSecond.length == 1) {
			curSecond = "0" + curSecond;
		}

		var fileName = title + "_" + curYear + curMonth + curDate + "_"
			+ curHour + curMinute + curSecond + ".xlsx";
		//alert(fileName);
		return fileName;
	}
	function doFileExport(inName, inStr) {
		/*var oXL = new ActiveXObject("Excel.Application");
		var oWB = oXL.Workbooks.Add();
		var oSheet = oWB.ActiveSheet;
		var sel = document.body.createTextRange();
		sel.moveToElementText(inStr);
		sel.select();
		sel.execCommand("Copy");
		oSheet.Paste();

		var sheetR = oSheet.UsedRange.Rows.Count;
		var sheetC = oSheet.UsedRange.Columns.Count;
		oSheet.Range(oSheet.Cells(1, 1), oSheet.Cells(sheetR, sheetC)).Borders.LineStyle = 1;
		oSheet.Range(oSheet.Cells(1, 1), oSheet.Cells(sheetR, sheetC)).Font.Size = 9;

		oSheet.Range(oSheet.Cells(1, 1), oSheet.Cells(1, sheetC)).Merge();

		oSheet.Cells(2, 1).HorizontalAlignment = 2;
		oSheet.Cells(2, 1).VerticalAlignment = 2;
		oSheet.Cells(2, 1).Font.Bold = true;
		oSheet.Cells(2, 1).Font.Size = 12;
		oSheet.Rows(2 + ":" + 2).RowHeight = 30;
		oSheet.Range(oSheet.Cells(2, 1), oSheet.Cells(2, sheetC)).Merge();
		oXL.Visible = true;
		alert("导出成功");*/

		var xlsWin = null;
		if (!!document.all("HideFrm")) {
			xlsWin = HideFrm;
		}
		else {
			var width = 6;
			var height = 4;
			var openPara = "left=" + (window.screen.width / 2 - width / 2)
				+ ",top=" + (window.screen.height / 2 - height / 2)
				+ ",scrollbars=no,width=" + width + ",height=" + height;
			xlsWin = window.open("", "_blank", openPara);
		}
		xlsWin.document.write(inStr);
		xlsWin.document.close();
		xlsWin.document.execCommand('Saveas', true, inName);
		xlsWin.close();
	}

});

